<?php
namespace app\admin\controller;

use app\common\model\ChangguanFenleiChangdi as ChangguanFenleiChangdiModel;

class ChangguanFenleiChangdi extends Base
{
    public function __construct () {
        parent::__construct();
    }

    /**
     * 列表
     * @return \think\response\Json
     */
    public function fenleilist(){
        $where = array('pid'=>0);
        //数据
        $list = ChangguanFenleiChangdiModel::getAll($where);
        //
        if($list){
            foreach($list as $k=>$v){
                $children = ChangguanFenleiChangdiModel::getAll(array('pid'=>$v['id']));
                $list[$k]['children'] = $children?$children:[];
            }
        }

        //返回
        return returnJson(0,'',$list?$list:[]);
    }

    /**
     * 详情
     * @return \think\response\Json
     */
    public function detail(){
        $where = array('id'=>input('id',0));
        //数据
        $detail = ChangguanFenleiChangdiModel::getOne($where);

        //返回
        return returnJson(0,'',$detail);
    }

    /**
     * 所有分类
     * @return \think\response\Json
     */
    public function allfenlei(){
        $where = array('pid'=>array('eq',0));
        //数据
        $list = ChangguanFenleiChangdiModel::getAll($where);
        //返回
        return returnJson(0,'',$list?$list:[]);
    }

    /**
     * 新增、编辑
     * @return \think\response\Json
     */
    public function edit(){

        if(request()->isPost()){

            $save = array(
                'label' => input('label'),
                'pid' => input('pid')
            );

            $detail = ChangguanFenleiChangdiModel::getOne($save);

            if($detail){
                return returnJson(1,'该分类已存在');
            }

            $save['update_time'] = time();
            if(input('id')){
                $where['id'] = input('id');
                ChangguanFenleiChangdiModel::update($save,$where);
            }else{
                $save['create_time'] = time();
                ChangguanFenleiChangdiModel::setInsertGetId($save);
            }
            return returnJson(0,'success');
        }
        //返回
        return returnJson(0,'');
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function delete()
    {
        if (input('id', 0)) {
            //查询条件
            $where['id'] = input('id');

            //删除记录
            ChangguanFenleiChangdiModel::setDel($where);
        }
        return returnJson(0, '');

    }

}
